/**
 * Created by hxpeng on 2017/5/18.
 */
(function () {
    'use strict';

    angular.module('App.pages.member')
        .controller('AddAlbumCtrl', AddAlbumCtrl);

    function AddAlbumCtrl($scope,AppUtils,$location,$http,Global,MemberModel,$state) {
        var vm = this;
        vm.imgIndex = 0;//imgUrl中保存的图片唯一标识符
        vm.imgUrl = [];//页面预览图片数组
        vm.postImgArray = [];//提交后台图片serverId数组
        $scope.localIds = "";


        $scope.$on('$ionicView.enter', function(){
            var currentPath = $location.url();
            if(currentPath.indexOf("#") != -1){
                currentPath = currentPath.split('#')[0];
            }
            currentPath = Global.path.wechat_path + currentPath;
            $http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
                .success(function(data){
                    wx.config({
                        debug: false,
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.noncestr,
                        signature: data.signature,
                        jsApiList: ['scanQRCode','chooseImage','previewImage','uploadImage']
                    });
                    wx.ready(function(){
                        console.log(1);
                    });
                    wx.error(function(res){
                        alert(JSON.stringify(res));
                        console.log(res);
                    });
                })
                .error(function(data,header,config,status){
                    alert("请求微信sdk校验异常");
                });
        });



        $scope.chooseImg = function(){
            wx.chooseImage({
                count: 9,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: function (res) {
                    var localIds = res.localIds;
                    syncPutImg(localIds);
                    AppUtils.loading();
                }
            });
        }

        //同步上传图片
        var syncPutImg = function(localIds){
            var img = localIds.pop();
            wx.uploadImage({
                localId: img,
                isShowProgressTips: 0,
                success: function (res) {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    var obj = {};
                    obj.imgIndex = vm.imgIndex;
                    obj.url = img;
                    obj.serverId = serverId;
                    $scope.$apply(function(){
                        vm.imgUrl.push(obj);
                    });
                    vm.imgIndex++;
                    if(localIds.length > 0){
                        syncPutImg(localIds);
                    }else{
                        AppUtils.loadfinish();
                    }
                }
            });
        };

        //大图片预览
        $scope.previewImg = function(url){
            var imgArray = [];
            angular.forEach(vm.imgUrl, function(obj, index) {
                imgArray.push(obj.url);
            });
            wx.previewImage({
                current: url,
                urls: imgArray
            });
        }

        //删除选择的图片
        $scope.removePicture = function(url,imgIndex){
            var urlIndex = null;
            angular.forEach(vm.imgUrl, function(obj, index) {
                if (obj.url === url && obj.imgIndex === imgIndex) {
                    urlIndex = index;
                }
            });
            $scope.$apply(function(){
                vm.imgUrl.splice(urlIndex, 1);
            });
        }


        $scope.uploadImg = function(){
            if(!AppUtils.isUndefinedOrNull(vm.imgUrl)){
                angular.forEach(vm.imgUrl, function(obj, index) {
                    if (!AppUtils.isUndefinedOrNull(obj.serverId)) {
                        vm.postImgArray.push(obj.serverId);
                    }
                });
            }
            MemberModel.submitUploadImg({serverIds: JSON.stringify(vm.postImgArray)}).$promise.then(function(response){
                if(response.stat == 'success'){
                    AppUtils.showAlert("提交成功！");
                    $state.go("memberMenu.albumIndex");
                }else if(response.stat == 'err'){
                    AppUtils.showAlert("提交失败:" + response.msg);
                }
            });
        }

    }

})();